<?php
namespace app\admin\controller;

use app\admin\model\Category as CategoryModel;

class Category extends Base
{
    /**
     * 分类首页
     * @return mixed
     */
    public function index(){
        return $this->fetch();
    }

    /**
     * 获取列表或某个分类详情
     */
    public function getList(){
        $param = $this->request->only('id');
        $category = new CategoryModel();
        //获取信息
        if ($param){
            $list = $category->getDetailById($param['id']);
        }else{
            $list = $category->getDetail();
        }
        if ($list){
            $this->success('获取成功。', null, $list);
        }
        $this->error('获取失败！');
    }

    /**
     * 添加分类
     */
    public function add(){
        $param = $this->request->param();
        $category = new CategoryModel();
        //插入数据
        $result = $category->allowField(true)->save($param);
        if ($result){
            $this->success('添加成功。', null, $category->getLastInsID());
        }
        $this->error('添加失败！');
    }

    /**
     * 编辑分类信息
     */
    public function edit(){
        $param = $this->request->param();
        $where = $this->request->only('id');
        $category = new CategoryModel();
        //更新数据
        $result = $category->allowField(true)->save($param, $where);
        if ($result !== false){
            $this->success('更新成功。');
        }
        $this->error('更新失败！');
    }

    /**
     * 删除分类
     */
    public function delete(){
        $param = $this->request->only('id');
        $detail = CategoryModel::get($param['id']);
        //判断
        if ($param['id'] < 1){
            $this->error('非法参数！');
        }
        if (!$detail){
            $this->error('该分类不存在！');
        }
        if ($detail->hasSonNode($param['id'])){
            $this->error('请先删除子类！');
        }
        //是否存在文章
        $article = $detail->article();
        if ($article->count() > 0){
            $this->error('请先删除文章！');
        }
        //todo:是否有权限删除
        //硬删除
        $result = $detail->delete();
        if ($result){
            $this->success('操作成功。');
        }
        $this->error('操作失败！');
    }

}